package com.tsing.cli.common.core.util;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 线程工具类
 *
 * @author TheTsing
 */
@Slf4j
public class ThreadUtils {

    /**
     * sleep 等待，单位为毫秒
     */
    public static void sleep(long milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException ignore) {
        }
    }

    /**
     * 停止线程池
     */
    public static void shutdownAndAwaitTermination(ExecutorService executor) {
        if (null != executor && !executor.isShutdown()) {
            executor.shutdown();
            try {
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    executor.shutdownNow();
                    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                        log.error("Thread pool tasks did not complete within the timeout period, forcing exit");
                    }
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

}
